<?php
/**
 * 车辆违章信息表
 * Created by PhpStorm.
 * User: LRChang
 * Date: 2018/5/30
 * Time: 20:06
 * Mail: hjklrchang@qq.com
 */

namespace app\adminapi\model;

use app\adminapi\filter\CarViolationFilter;
use app\base\exception\RecordNotFoundException;
use traits\model\SoftDelete;

class CarViolation extends  Common {
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    protected $type = [
        'pic_list' => 'array',
    ];

    /**
     * 获取车辆违章列表
     * @param $where
     * @param $fields
     * @param int $page
     * @param int $pagenum
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function listData($where, $fields, $page = 1, $pagenum = 20) {
        $filter = new CarViolationFilter($fields, $where);
        $condition = $filter->geFiltered();
        $where = $condition['where'];
        $fields = $condition['field'];
        $mark = $filter->getMark();

        $buildQuery = function($query) use ($where) {
            self::authCompanyQuery($query, $where, 'company_id');
        };

        $result = [];
        $result['count'] = $this->where($buildQuery)->count();
        $result['list'] = $this->where($buildQuery)
            ->page($page, $pagenum)
            ->field($fields)
            ->order('violation_id desc')
            ->select();

        return array_merge($result, $mark);
    }

    /**
     * 新增或者编辑车辆违章
     * @param $params
     * @return $this|false|int
     * @throws RecordNotFoundException
     * @throws \think\exception\DbException
     */
    public function createOrUpdate($params) {
        $session = (new User())->getLoginUser();
        if(isset($params['violation_id'])) {

            $where = ['violation_id' => $params['violation_id']];
            $buildQuery = function($query) use ($where) {
                self::authCompanyQuery($query, $where, 'company_id');
            };

            $violation = self::get($buildQuery);
            if(!$violation) {
                throw new RecordNotFoundException();
            }

            // 当状态改为已处理，记录处理时间
            if($params['handle_status'] === '2' && $violation->getAttr('handle_status') !== '2' ) {
                $params['handle_time'] = date('Y-m-d H:i:s');
            }

            if($params['handle_status'] === '1'){
                $params['handle_time'] = null;
            }
        }elseif(!self::isSuperAdmin($session) && $session['user']['company_id']) {
            $params['company_id'] = $session['user']['company_id'];
        }

        if(isset($params['pic_list']) && $params['pic_list'] === ''){
            $params['pic_list'] = [];
        }

        // 补全关联字段
        $this->addRelativeFields( $params, 'app\adminapi\model\Company', $params['company_id'],  ['company_name'], '关联单位不存在');
        $this->addRelativeFields( $params, 'app\adminapi\model\Car', $params['car_id'],  ['number'=>'plate_no'], '关联车辆不存在');
        $this->addRelativeFields( $params, 'app\adminapi\model\Driver', $params['driver_id'],  ['name'=>'driver_name', 'phone'=>'driver_phone', 'id_card'=>'license_code'], '关联驾驶员不存在');

        if(isset($params['violation_id'])) {
            return $this->isUpdate(true)->save($params);
        }

        // 当状态为已处理，记录处理时间
        if($params['handle_status'] === '2' ) {
            $params['handle_time'] = date('Y-m-d H:i:s');
        }
        $this->save($params);
        return $this;
    }

}